<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/screenCode'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  kfIcon: '',
  kfPop: '',
  actJson: '',
  status: 0,
  desp: '',
})

const rules = reactive({
  kfIcon: [
    { required: true, message: '请上传客服图标', trigger: 'blur' },
  ],
  kfPop: [
    { required: true, message: '请上传客服弹窗图', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
})

// const openTypeArray = reactive([
//   { value: 1, label: '每月' },
//   { value: 2, label: '每周' },
// ])

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(url: string, key: string, index?: number) {
  if (key === 'list') {
    ruleForm.value.actJson[index!].pic = url
  }
  else {
    ruleForm.value[key] = url
  }
}

function AddCard() {
  (ruleForm.value.actJson as any[]).push({
    pic: '',
    link_url: '',
  })
}

// 提交
async function SubmitData(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      const params = {
        ...ruleForm.value,
      }
      params.actJson = JSON.stringify(params.actJson)

      if (id) {
        // 编辑
        params.id = id
        PutModifyData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('编辑成功')
            router.push({ name: 'ScreenCodeActList' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`编辑失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`编辑失败。${errorStr}`)
            }
          }
        })
      }
      else {
        // 添加
        PostCreateData(params).then((res: any) => {
          if (res.statusCode === 200) {
            ElMessage.success('添加成功')
            detailData.emptyFormData('ScreenCodeActFrom')
            router.push({ name: 'ScreenCodeActList' })
          }
          else {
            if (typeof res.errors === 'string') {
              ElMessage.error(`添加失败。${res.errors}`)
            }
            else {
              let errorStr = ''
              for (const key in res.errors) {
                errorStr += `${key}：${res.errors[key]}；`
              }
              ElMessage.error(`添加失败。${errorStr}`)
            }
          }
        })
      }
    }
  })
}

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.actJson = JSON.parse(ruleForm.value.actJson as string)
      }
    })
  }
  else {
    // ruleForm.value = detailData.GetMemberholiday()
    ruleForm.value = detailData.getFormData('ScreenCodeActFrom')
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('ScreenCodeActFrom', newValue)
    }
  }, { deep: true })
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="5">
            <ElFormItem label="状态">
              <el-switch
                v-model="ruleForm.status"
                :active-value="1"
                :inactive-value="0"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="19">
            <ElFormItem label="描述">
              <el-input v-model="ruleForm.desp" placeholder="请输入描述" style="max-width: 500px;" type="textarea" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="客服图标" prop="kfIcon">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.kfIcon" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'kfIcon')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="客服弹窗图" prop="kfPop">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.kfPop" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'kfPop')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="关联活动">
        <ElRow :gutter="20">
          <el-button v-if="ruleForm.actJson.length === 0" type="success" @click="AddCard">
            新增
          </el-button>
          <ElCol v-for="(item, index) in ruleForm.actJson" :key="index" :md="8">
            <el-card>
              <ElFormItem label="">
                <el-input v-model="item.link_url" placeholder="请输入链接" />
              </ElFormItem>
              <ElFormItem label="">
                <ImageUpload
                  width="auto" height="200" :size="5" :url="item.pic" :ext="['jpg', 'png']"
                  @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'list', index)"
                />
              </ElFormItem>
            </el-card>
          </elcol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData(ruleFormRef)">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
